package base.interesting;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Stream;

/**
 * @program JavaBase
 * @description:
 * @author: zhanglu
 * @create: 2020-04-09 14:46:00
 */
public class StringTest {

    private ReentrantLock lock = new ReentrantLock();

    public static void main(String[] args) {
//        test01();
        test0203();
    }

    public static void test01(){
        /**
         intern()实现不会复制实例，只是在常量池中记录首次出现的实例引用
         java这个字符串在 System类——>initializeSystemClass()­——>sun.misc.Version.init();——>Version类中存在private static final String launcher_name = "java";
         java字符串在str2之前已经出现过，加载到运行常量池中。
         */
        String s1 = new StringBuilder("计算机").append("软件").toString();
        System.out.println(s1.intern() == s1);
        String s2 = new StringBuilder("ja").append("va").toString();
        System.out.println(s2.intern() == s2);

        String s3 = new StringBuilder("计算机").append("软件").toString();
        System.out.println(s3.intern() == s1);
        System.out.println(s3.intern() == s3);


        System.out.println(s1 == s2);
        System.out.println(s1.intern() == s2);

    }

    private int count = 0;

    public static void test0203(){
        StringTest test = new StringTest();

        Runnable r1 = () -> test.test02("01");
        Runnable r2 = () -> {
            for (int i = 0; i < 10; i++) {
                try {
                    TimeUnit.MILLISECONDS.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                test.test03("02");
            }
        };

        new Thread(r2, "D").start();
        new Thread(r1, "A").start();
        new Thread(r2, "B").start();
        new Thread(r2, "C").start();

    }

    public void test02(String s){
        lock.lock();
        try {
//            TimeUnit.MILLISECONDS.sleep(100);
            System.out.println(Thread.currentThread().getName() + ":" + s);
            if(count == 10){
                return;
            }
            count ++;
            test02(s);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void test03(String s){
        lock.lock();
        try {
//            TimeUnit.MILLISECONDS.sleep(100);
            System.out.println(Thread.currentThread().getName() + ":" + s);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

}
